<template>
  <div class="code-main">
    <ActionBar :page-no="163" :add-active="addActive" :del-active="delActive" :cancel-active="cancelActive"
      :edit-active="editActive" :has-edit="false" :has-del="false" :save-active="saveActive" @add="save" @cancel="cancel"
      @edit="edit" @del="del" @save="save" />
    <div class="code-view" @dragenter.prevent @dragover.prevent>
      <div class="codebox">
        <div class="codebox-left">
          <div class="codebox-left-title pad-left-25">条码类型</div>
          <div class="code-sty">
            <div class="select">
              <div class="select-name">选择条码类型：</div>
              <el-select filterable clearable size="mini" v-model="noType" placeholder  @change="gethaveseetcoderule">
                <el-option v-for="(nu, index) in noTypelist" :key="index" :label="nu.noTypeName" :value="nu.noType" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="codebox-left">
          <div class="codebox-left-title pad-left-25">条码组件</div>
          <div v-if="drogstau1" id="leftref" ref="leftref" class="code-sty">
            <div v-for="(item, index) in defaultLeftxyList" :key="item.id" class="newmove" :draggable="codeboxleftstau"
              @dragend.stop="moveend($event, item)">
              <div v-if="item.type === 21 || item.type === 22 || item.type === 23" class="mczilong-sty">{{ item.name }}
              </div>
              <div v-if="item.type === 2" class="sel-sty">
                固定首字符：
                <input :ref="`zhinput${index}`" v-model="item.value" class="zh-input" @click="inputClicked(index)" />
              </div>
              <div v-if="item.type === 3" class="sel-sty">
                连续数字位数：
                <el-select filterable clearable v-model="item.value" placeholder>
                  <el-option v-for="nu in numberlist" :key="nu" :label="nu" :value="nu" />
                </el-select>
              </div>
            </div>
          </div>
        </div>
        <div class="codebox-right">
          <div class="lin-sty pad-left-25">当前条码类型规则：{{ havesetmessage }}</div>
          <div class="lin-sty pad-left-25">条码规则预览：{{ nowmessage }}</div>
          <div class="line-title pad-left-25">条码顺序</div>
          <div v-if="drogstau2" id="rightref" ref="rightref" class="sort-box">
            <div v-for="(itemtwo, indextwo) in defaultLeftxyListtwo" :key="indextwo" class="newmovetwo"
              :draggable="codeboxleftstau" @dragend.stop="moveendtwo($event, itemtwo, indextwo)">
              <div v-if="itemtwo">
                <div v-if="itemtwo.type === 21 ||
                  itemtwo.type === 22 ||
                  itemtwo.type === 23
                  " class="mczilong-sty">{{ itemtwo.name }}</div>
                <div v-if="itemtwo.type === 121 ||
                  itemtwo.type === 122 ||
                  itemtwo.type === 123
                  " class="mczilong-sty">{{ itemtwo.name }}</div>
                <div v-if="itemtwo.type === 2" class="sel-sty">
                  固定首字符：
                  <input :ref="`zhinput${indextwo}`" v-model="itemtwo.value" class="zh-input"
                    @click="inputClicked(indextwo)" />
                </div>
                <div v-if="itemtwo.type === 3" class="sel-sty">
                  连续数字位数：
                  <el-select filterable clearable v-model="itemtwo.value" placeholder>
                    <el-option v-for="nu in numberlist" :key="nu" :label="nu" :value="nu" />
                  </el-select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="del-box">
        <div class="line-title pad-left-25">删除区域</div>拖拽此区域删除
      </div>
    </div>
  </div>
</template>
<script>
import ActionBar from "@/components/ActionBar/index.vue";
import { mymixin } from "@/utils/mixins";
import ConfigCodeApi from "@/api/basic-info-manage/config-code";
import NoTypeApi from "@/api/basic-info-manage/no-type";
export default {
  name: "CodingManagement",
  components: {
    ActionBar
  },
  mixins: [mymixin],
  data () {
    return {
      havesetmessage: "暂未配置", // 获取配置好的条码规则
      name: "ppp",
      intnumber: "1", // 当前选择的数字位数
      fistzimu: "G", // 首字符
      numberlist: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      drogstau1: true,
      drogstau2: true,
      // 当前拖拽标识
      nowdargingindex: -1,
      // 拖拽时移动到当前区域，展示状态
      codeboxleftstau: true,
      codeboxrightstau: false,
      // 默认拖拽位置
      defaultLeftxyList: [
        {
          id: 1,
          type: 22,
          sortnum: 1,
          value: "yyyymmdd",
          name: "yyyy-mm-dd(年-月-日)",
          left: 100,
          top: 10,
          w: 200,
          active: false
        },
        {
          id: 2,
          type: 22,
          sortnum: 6,
          value: "yyyymm",
          name: "yyyy-mm(年-月)",
          left: 310,
          top: 10,
          w: 200,
          active: false
        },
        {
          id: 3,
          type: 22,
          sortnum: 3,
          value: "mmdd",
          name: "mm-dd(月-日)",
          left: 100,
          top: 40,
          w: 200,
          active: false
        },
        {
          id: 4,
          type: 2,
          sortnum: 4,
          value: "",
          name: "固定首字符",
          left: 310,
          top: 40,
          w: 200,
          active: false
        },
        {
          id: 5,
          type: 3,
          sortnum: 5,
          value: "",
          name: "连续数字位数",
          left: 100,
          top: 70,
          w: 200,
          active: false
        }
      ],
      // 已有选项
      defaultLeftxyListtwo: [
        // { id: 1, type: 2, sortnum: 1, name: "固定首字符", value: "", left: 20, top: 10, w: 200, active: false },
        // { id: 2, type: 22, sortnum: 2, value: "yyyymm", name: "yyyy-mm(年-月)", left: 230, top: 10, w: 200, active: false },
        // { id: 5, type: 3, sortnum: 3, value: "", name: "连续数字位数", left: 20, top: 40, w: 200, active: false }
      ],
      currentFieldIndex: null,
      currentFieldIndextwo: null,
      zhyidonglist: {},
      currentField: {},
      clicknum: 0,
      lishilist: {
        left: 0,
        top: 0
      },
      noTypelist: [
        {
          noTypeName: "码单号",
          noType: "productionBatch"
        }
      ],
      noType: "productionBatch"
    };
  },
  computed: {
    // 返回展示值
    nowmessage: function () {
      let mes = "";
      if (this.defaultLeftxyListtwo[0]) {
        this.defaultLeftxyListtwo.forEach(item => {
          if (item.type && item.type === 2) {
            mes = mes + item.value;
          }
        });
        this.defaultLeftxyListtwo.forEach(item => {
          if (item.type && item.type === 22) {
            mes = mes + item.value;
          }
        });
        this.defaultLeftxyListtwo.forEach(item => {
          if (item.type && item.type === 3) {
            mes = mes + item.value;
          }
        });
      }

      return mes;
    }
  },
  watch: {
    nowChanceStau (newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === "add") {
        this.codeboxleftstau = true;
      }
      if (newval === "") {
        this.setFieldProperties();
        this.codeboxleftstau = false;
      }
    },
  },
  mounted () {
    this.gethaveseetcoderule();
    this.gethaveset();
  },
  methods: {
    noTypeChange (e) {
      console.log(e);
    },
    // 获取类数据
    gethaveset () {
      NoTypeApi.queryByCondition().then(res => {
        this.noTypelist = res.data;
      })
    },
    moveend (event, item) {
      const e = event || window.event;
      let top = e.layerY;
      if (top > 110) {
        // this.$message.success("拖动到高度外了")
      } else {
        //  this.$message.warning("在里面")
      }
      // 当前容器宽度
      let nowwidth = document.getElementById("leftref").offsetWidth;
      let x = e.layerX;
      if (x < nowwidth && top > 200) {
        if (this.defaultLeftxyListtwo.length >= 8) {
          this.$message.warning("超过最大可添加数量！");
        } else {
          this.defaultLeftxyListtwo.push(item);
          this.setFieldProperties();
          this.$message.success("添加成功！");
        }
      } else if (x > nowwidth) {
        this.$message.warning("拖动到条码顺序区域");
      } else {
        this.$message.error("原地不要拖动");
      }
    },
    // 条码顺序
    moveendtwo (event, item, i) {
      console.log(event);
      const e = event || window.event;

      let top = e.layerY;
      if (top > 110) {
        // this.$message.success("拖动到高度外了")
      } else {
        //  this.$message.warning("在里面")
      }
      // 当前容器宽度
      let nowwidth = document.getElementById("rightref").offsetWidth;
      let nowheight = document.getElementById("rightref").offsetHeight;
      let x = e.layerX;
      if (x < nowwidth && top > 0 && top < nowheight) {
        //  if (this.defaultLeftxyListtwo.length >= 8) {
        //     this.$message.warning("超过最大可添加数量！");
        //  }else{
        //    this.defaultLeftxyListtwo.push(item)
        this.$message.success("在展示区域！");
        //  }
      } else if (x > nowwidth) {
        this.defaultLeftxyListtwo.splice(i, 1);
        // delete this.defaultLeftxyListtwo[i]
        this.$message.success("删除成功！");
        this.setFieldProperties();
      } else {
        this.$message.error("请不要拖动到其他区域");
      }
    },
    // 获取已配置当前的条码规则
    gethaveseetcoderule (e) {
      const params = {}
      if (e) params.noType = e
      ConfigCodeApi.queryByCondition(params).then(res => {
        let listone = res.data[0];
        if (listone?.noRule) {
          let listtwo = JSON.parse(listone?.noRule);
          let newobj = "";
          listtwo.forEach((item, index) => {
            for (let key in item) {
              newobj += item[key];
            }
          });
          this.havesetmessage = newobj;
        } else {
          this.havesetmessage = '暂未配置'
        }
      });
    },
    // 输入框点聚焦
    inputClicked (i) {
      if (this.nowChanceStau === "") {
        let name = `zhinput${i}`;
        this.$refs[name][0].focus();
      }
    },
    onActivated (index) {
      this.currentFieldIndex = index;
      // this.currentField.left = this.defaultLeftxyList[this.currentFieldIndex].left;
      // this.currentField.top = this.defaultLeftxyList[this.currentFieldIndex].top;
      // console.log(this.currentField);
    },
    onActivatedtwo (index) {
      this.currentFieldIndextwo = index;
      this.clicknum += 1;
    },
    // 返回拖拽起始位置
    setFieldProperties () {
      this.drogstau1 = false;
      this.drogstau2 = false;
      setTimeout(() => {
        this.drogstau1 = true;
        this.drogstau2 = true;
      }, 10);
    },
    // 排序方法一主要用于添加排序
    zhsortmet (rect, zz) {
      let draginglist = { top: "", left: "" };
      draginglist.top = rect.top - 25;
      draginglist.left = rect.left - 690;
      if (this.currentFieldIndex !== null) {
        var sorterlist = {
          type: this.defaultLeftxyList[this.currentFieldIndex].type,
          left: draginglist.left,
          top: draginglist.top,
          value: this.defaultLeftxyList[this.currentFieldIndex].value,
          name: this.defaultLeftxyList[this.currentFieldIndex].name,
          w: this.defaultLeftxyList[this.currentFieldIndex].w,
          id: this.defaultLeftxyListtwo.length + 1,
          active: false
        };
        if (zz && zz === "nowdarging") {
          // 表示当前此块正在被拖拽
          sorterlist["nowdarging"] = true;
        }
      }
      let list = this.defaultLeftxyListtwo;
      // let nowobj = this.sorterlist
      list.forEach(item => {
        if (item.top >= draginglist.top && item.left >= draginglist.left) {
          if (!sorterlist.sortnum || sorterlist.sortnum >= item.sortnum) {
            sorterlist.sortnum = item.sortnum - 1;
          }
        } else {
          if (!sorterlist.sortnum || sorterlist.sortnum <= item.sortnum) {
            sorterlist.sortnum = item.sortnum + 1;
          }
        }
      });
      this.defaultLeftxyListtwo.push(sorterlist);
      this.zhsortmettwo();
    },
    // 排序方法二主要用于位置调整
    zhsortmetgg (rect, zz, mes) {
      if (zz && zz === "nowdarging" && this.nowdargingindex === -1) {
        this.lishilist = mes;
      }
      let yidongwidth = this.lishilist.left - rect.left;
      let yidongheigh = this.lishilist.top - rect.top;
      if (
        yidongwidth < 250 &&
        yidongwidth > -200 &&
        yidongheigh > -30 &&
        yidongheigh < 30
      ) {
        // 在此范围内不更新数据
        return;
      }
      let list = this.defaultLeftxyListtwo;
      // console.log(list)
      if (list.length > 0) {
        for (var myll = 0; myll < list.length; myll++) {
          if (list[myll]["top"] > rect.top && list[myll]["left"] > rect.left) {
            this.defaultLeftxyListtwo[this.currentFieldIndextwo].sortnum =
              list[myll]["sortnum"] - 1;
            break;
          }
        }
      }
      // 到这一步才算拿到了实时的位置index
      if (zz && zz === "nowdarging" && this.nowdargingindex === -1) {
        this.defaultLeftxyListtwo[this.currentFieldIndextwo][
          "nowdarging"
        ] = true;
      } else if (this.nowdargingindex >= 0) {
        this.defaultLeftxyListtwo[this.nowdargingindex]["nowdarging"] = true;
      }
      this.zhsortmettwo();
    },
    // 根据序号来排位置
    zhsortmettwo () {
      let list = this.defaultLeftxyListtwo;
      list.sort(function (a, b) {
        if (a.sortnum < b.sortnum) {
          return -1;
        } else if (a.sortnum > b.sortnum) {
          return 1;
        }
        return 0;
      });
      for (let i = 0; i < list.length; i++) {
        if (i === 0) {
          list[i].top = 10;
          list[i].left = 20;
        } else {
          if (i % 2 === 0) {
            list[i].top = (i / 2) * 30 + 10;
            list[i].left = 20;
          } else if (i % 2 === 1) {
            list[i].top = ((i + 1) / 2 - 1) * 30 + 10;
            list[i].left = 230;
          }
        }
      }
      // 如果是拖拽状态获取当前的的idnex,然后删除nowdarging标识
      list.forEach((item, index) => {
        if (item.nowdarging && item.nowdarging === true) {
          this.nowdargingindex = index;
          item.nowdarging = false;
        }
      });
      this.defaultLeftxyListtwo = list;
    },
    save () {
      let jklist = this.defaultLeftxyListtwo;
      let paramlist = [];
      jklist.forEach(item => {
        if (item.type === 22) {
          paramlist.push({ Date: item.value });
        }
        if (item.type === 2) {
          paramlist.push({ String: item.value });
        }
        if (item.type === 3) {
          paramlist.push({ int: item.value });
        }
      });
      const hjk = JSON.stringify(paramlist);
      let noType = "productionBatch";
      noType = this.noType;
      ConfigCodeApi.add(hjk, noType).then(res => {
        if (res.success) {
          this.gethaveseetcoderule();
          this.resetActionBar();
          this.$message.success("添加成功！");
        } else {
          this.$message.warning("添加失败！");
          this.resetActionBar();
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.field {
  position: absolute;
  padding: 3px;
  display: flex;
}

.code-main {
  width: 100%;
  height: 100%;

  .code-view {
    width: 100%;
    height: 100%;
    // padding: 20px;
    display: flex;
    // border: 1px solid $borderColor;
    height: calc(100% - #{$actionBarHeight + 10});
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
    align-items: center;
    justify-content: center;

    // background: rgb(162, 167, 162);
    .pad-left-25 {
      padding-left: 5px;
    }

    .codebox {
      width: 50%;
      height: 95%;
      // padding: 20px;
      display: flex;
      // border: 1px solid $borderColor;
      display: flex;
      flex-wrap: nowrap;
      flex-direction: column;
      // align-items: center;
      // justify-content: center;
      // background: rgb(40, 177, 182);
    }

    .del-box {
      width: 49%;
      border: 1px solid #2D8EEB;
      border-radius: 10px;
      height: 95%;
      margin-left: 1%;
      background-color: rgba(0, 0, 0, 0.2);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      position: relative;

      .line-title {
        width: 150px;
        height: 40px;
        // line-height: 40px;
        text-align: center;
        font-size: 22px;
        position: absolute;
        left: 50%;
        top: -20px;
        background-color: #00485a;
        border: 1px solid #2D8EEB;
        color: #fff;
        border-radius: 9px;
        padding: 5px 10px;
        transform: translateX(-50%);
      }
    }

    .del-box:hover {
      color: rgb(204, 35, 23);
    }
  }
}

.codebox-left {
  width: 100%;
  height: 200px;
  // border: 1px;
  border: 1px solid #2D8EEB;
  border-radius: 10px;
  margin-bottom: 40px;
  // background: rgb(190, 46, 46);
  // display: flex;
  // white-space: nowrap;
  padding: 30px 10px 10px;
  box-sizing: border-box;
  position: relative;

  .codebox-left-title {
    width: 150px;
    height: 40px;
    // line-height: 40px;
    text-align: center;
    font-size: 22px;
    position: absolute;
    left: 50%;
    top: -20px;
    background-color: #00485a;
    border: 1px solid #2D8EEB;
    color: #fff;
    border-radius: 9px;
    padding: 5px 10px;
    transform: translateX(-50%);
  }

  .code-sty {
    // position: relative;
    width: 100%;
    height: 100%;
    // margin-bottom: 10px;
    border-radius: 10px;
    border: 1px solid #2D8EEB;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    line-height: 20px;
    justify-content: flex-start;
    align-items: center;
    position: relative;

    .select {
      display: flex;
      align-items: center;
      margin-left: 10px;
    }

    .newmove {
      width: 33%;
      height: 30px;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: center;
      // background: #fff;
      margin: 0;
      // position: absolute;
    }
  }
}

.codebox-right {
  // 由于要拖动获取固定px,不能用百分比处理
  // 由于升级了可以用百分比了
  width: 100%;
  border: 1px solid #2D8EEB;
  height: calc(100% - 200px);
  border-radius: 10px;
  box-sizing: border-box;
  padding: 30px 10px 10px;
  // background: rgb(27, 172, 164);
  position: relative;

  .lin-sty {
    color: #000;
    height: 25px;
    line-height: 25px;
    white-space: nowrap;
  }

  .line-title {
    width: 150px;
    height: 40px;
    // line-height: 40px;
    text-align: center;
    font-size: 22px;
    position: absolute;
    left: 50%;
    top: -20px;
    background-color: #00485a;
    border: 1px solid #6ff;
    color: #fff;
    border-radius: 9px;
    padding: 5px 10px;
    transform: translateX(-50%);
  }

  .sort-box {
    width: 100%;
    height: calc(100% - 50px);
    border: 1px solid #58b495;
    border-radius: 9px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-content: flex-start;
    position: relative;

    .newmovetwo {
      width: 33.3%;
      height: 30px;
      display: flex;
      margin-top: 20px;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}

.sel-sty {
  width: 180px;
  height: 25px;
  line-height: 25px;
  display: flex;
  white-space: nowrap;
  cursor: pointer;

  ::v-deep .el-input__inner {
    height: 25px;
    line-height: 25px;
    border: 1px solid #dcdfe6;
  }

  ::v-deep .el-input__icon {
    line-height: 40px !important;
  }
}

.zh-input {
  background-color: transparent;
  border: 1px solid #dcdfe6;
  color: #fff;
  width: calc(100% - 50px);
  outline: none;
}

.mczilong-sty {
  width: 180px;
  height: 25px;
  background-color: #00485a;
  text-align: center;
  line-height: 25px;
  white-space: nowrap;
  cursor: pointer;
}

.vdr.active:before {
  outline: none;
}
</style>
